/**
 * @Author: easten
 * @Created: 2024-04-15 23:48:14
 * @Description:
 *
 */
import { ApiDeviceConfig } from "_common/api/iot";
import { DrawerProps } from "_common/DataType";
import {
  IotAlarmConfig,
  IotDeviceConfig,
  IotSensorGroup,
} from "_common/entity";
import { AxiosInstance } from "axios";
import React, { useState, useEffect, useMemo, useRef } from "react";
import {
  Alert,
  Divider,
  Drawer,
  Form,
  FormInstanceFunctions,
  Input,
  InputNumber,
  MessagePlugin,
  PrimaryTableCol,
  Switch,
  Table,
  Tag,
} from "tdesign-react";
import FormItem from "tdesign-react/es/form/FormItem";
import GreaseConfig from "./GreaseConfig";
type ProductConfigDrawerProps = DrawerProps & {
  axios: AxiosInstance;
};
const ProductConfigDrawer: React.FC<ProductConfigDrawerProps> = (
  props: ProductConfigDrawerProps
) => {
  const { open, axios, onSuccess, value } = props;
  const [deviceConfig, setDeviceConfig] = useState<IotDeviceConfig>();
  const [alarmConfigs, setAlarmConfigs] = useState<IotAlarmConfig[]>([]);
  const tableRef = useRef<any>(null);
  const formRef = useRef<FormInstanceFunctions>(null);
  const apiDeviceConfig = new ApiDeviceConfig(axios);

  useEffect(() => {
    return () => {
      formRef.current?.reset();
    };
  }, [open]);

  useEffect(() => {
    if (value && value.sensorGroups) {
      getConfigList();
      let configs = value?.sensorGroups?.map((item: IotSensorGroup) => {
        return {
          dtCode: value?.groupCode,
          stCode: item?.groupCode,
          enabled: false,
          warningValue: 0,
          alarmValue: 0,
          frequency: 0,
          offlineSpan: 0,
          saveSpan: 0,
          sensorGroup: item,
        };
      });
      setAlarmConfigs(configs);
    }
  }, [value]);

  const handleClose = () => {
    onSuccess?.(false);
  };

  // 获取配置项列表
  const getConfigList = async () => {
    const response = await apiDeviceConfig.getDeviceConfig(value?.groupCode);
    if (response && response.code == 200 && response.data) {
      let data = response.data;
      setDeviceConfig(data);
      formRef.current?.setFieldsValue(data);
      data?.alarmConfigs.forEach((item) => {
        setAlarmConfigs((pre) => {
          return pre.map((config) => {
            if (config.stCode == item.stCode) {
              return { ...config, ...item };
            }
            return config;
          });
        });
      });
    }
  };

  // 保存配置项

  const columns = useMemo(() => {
    return [
      {
        align: "left",
        width: 80,
        ellipsis: true,
        colKey: "index",
        title: "序号",
        cell: ({ rowIndex }) => {
          return <span>{rowIndex + 1}</span>;
        },
      },
      {
        align: "left",
        ellipsis: true,
        colKey: "sensorGroup.groupName",
        title: "物模型类型",
      },
      {
        align: "left",
        ellipsis: true,
        colKey: "stCode",
        title: "类型编码",
      },
      {
        align: "left",
        ellipsis: true,
        colKey: "sensorGroup.groupDesc",
        title: "物模型描述",
      },
      {
        align: "left",
        ellipsis: true,
        colKey: "warningValue",
        title: "预警开始值",
        edit: {
          component: Input,
          // props, 透传全部属性到 Input 组件
          props: {
            clearable: true,
            autofocus: true,
            defaultValue: 12,
          },
          // 触发校验的时机（when to validate)
          validateTrigger: "change",
          // 透传给 component: Input 的事件（也可以在 edit.props 中添加）
          on: (editContext) => ({
            onBlur: () => {
              console.log("失去焦点", editContext);
            },
            onEnter: (ctx: any) => {
              ctx?.e?.preventDefault();
            },
          }),
          // 除了点击非自身元素退出编辑态之外，还有哪些事件退出编辑态
          abortEditOnEvent: ["onEnter"],
          // 编辑完成，退出编辑态后触发
          onEdited: (context) => {
            alarmConfigs.splice(context.rowIndex, 1, context.newRowData);
            setAlarmConfigs([...alarmConfigs]);
          },
          // 校验规则，此处同 Form 表单
        },
        // 默认是否为编辑状态
        defaultEditable: false,
      },
      {
        align: "left",
        ellipsis: true,
        colKey: "alarmValue",
        title: "报警开始值",
        edit: {
          component: Input,
          // props, 透传全部属性到 Input 组件
          props: {
            clearable: true,
            autofocus: true,
            defaultValue: 12,
          },
          // 触发校验的时机（when to validate)
          validateTrigger: "change",
          // 透传给 component: Input 的事件（也可以在 edit.props 中添加）
          on: (editContext) => ({
            onBlur: () => {
              console.log("失去焦点", editContext);
            },
            onEnter: (ctx: any) => {
              ctx?.e?.preventDefault();
            },
          }),
          // 除了点击非自身元素退出编辑态之外，还有哪些事件退出编辑态
          abortEditOnEvent: ["onEnter"],
          // 编辑完成，退出编辑态后触发
          onEdited: (context) => {
            alarmConfigs.splice(context.rowIndex, 1, context.newRowData);
            setAlarmConfigs([...alarmConfigs]);
          },
          // 校验规则，此处同 Form 表单
        },
        // 默认是否为编辑状态
        defaultEditable: true,
      },
      {
        align: "center",
        fixed: "right",
        width: 140,
        colKey: "enabled",
        title: "是否启用报警",
        cell({ row }) {
          return (
            <span>
              {row.enabled ? (
                <Tag theme="success" variant="light-outline">
                  启用报警
                </Tag>
              ) : (
                <Tag theme="danger" variant="light-outline">
                  禁用报警
                </Tag>
              )}
            </span>
          );
        },
        edit: {
          component: Switch,
          // props, 透传全部属性到 Select 组件
          props: {
            clearable: true,
            label: ["启用报警", "禁用报警"],
          },
          // 除了点击非自身元素退出编辑态之外，还有哪些事件退出编辑态
          abortEditOnEvent: ["onChange"],
          // 编辑完成，退出编辑态后触发
          onEdited: (context) => {
            alarmConfigs.splice(context.rowIndex, 1, context.newRowData);
            setAlarmConfigs([...alarmConfigs]);
          },
        },
      },
    ] as PrimaryTableCol<IotAlarmConfig>[];
  }, [alarmConfigs]);

  const editableCellState = () => {
    return true;
  };

  // 加脂机的报警配置

  return (
    <Drawer
      header={`产品管理配置`}
      visible={open}
      sizeDraggable
      size="80%"
      onClose={handleClose}
      onCancel={handleClose}
      onConfirm={async () => {
        let formValues = formRef.current?.getFieldsValue(true);
        let data = {
          dtCode: value?.groupCode,
          enabled: value?.enabled,
          ...formValues,
          alarmConfigs,
        };
        const response = await apiDeviceConfig.createDeviceConfig(data);
        if (response && response.code == 200) {
          MessagePlugin.success("保存成功");
          handleClose();
        }
      }}
    >
      <Alert
        title="请根据实际监测的物模型类型进行配置，不要随意配置"
        theme="warning"
      />

      {value?.groupCode == 109 ? (
        <GreaseConfig />
      ) : (
        <>
          <Divider content="基本配置-默认缺省 3 分钟" align="left" />
          <Form ref={formRef} labelWidth={200}>
            <FormItem label="设备离线间隔" name="offlineSpan">
              <InputNumber value={deviceConfig?.offlineSpan} />
            </FormItem>
            <FormItem label="历史数据保存间隔" name="saveSpan">
              <InputNumber value={deviceConfig?.saveSpan} />
            </FormItem>
            <FormItem label="报警数据保存频率" name="frequency">
              <InputNumber value={deviceConfig?.frequency} />
            </FormItem>
          </Form>
          <Divider content="报警配置" align="left" />
          <Table<IotAlarmConfig>
            className="mt-5"
            bordered
            ref={tableRef}
            columns={columns}
            data={alarmConfigs}
            lazyLoad
            rowKey="stCode"
            verticalAlign="middle"
            editableCellState={editableCellState}
          />
        </>
      )}
    </Drawer>
  );
};
export default ProductConfigDrawer;
